package com.liu.audio.controller;


import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 测试功能
 */
@RestController
public class AudioController {


    private static String UPLOAD_DIR = "D:\\temp\\file";

    /**
     * 文件上传
     */
    @GetMapping("/audio")
    public void audio(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return;
        }

        try {
            // 确保上传目录存在
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 保存文件
            String fileName = file.getOriginalFilename();
            Path filePath = Paths.get(UPLOAD_DIR + fileName);
            Files.write(filePath, file.getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static String apikey = "--------";
    private static String model = "cosyvoice-v1";
    private static String voice = "longxiaochun";


    /**
     * 语音语音合成
     * @param message
     * @return
     */
    @GetMapping(value = "/audio-tts")
    public byte[] audioTTS(String message) {
        if (StringUtils.isEmpty(message)) {return new byte[]{};};

        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        // 若没有将API Key配置到环境变量中，需将下面这行代码注释放开，并将apiKey替换为自己的API Key
                        .apiKey(apikey)
                        .model(model)
                        .voice(voice)
                        .build();
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
        ByteBuffer audio = synthesizer.call(message);
//        System.out.print("requestId: " + synthesizer.getLastRequestId());
//        try (FileOutputStream fos = new FileOutputStream("D:\\output.mp3")) {
//            fos.write(audio.array());
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }

        return audio.array();
    }


}
